package com.example.eos.service;

import com.example.eos.bean.ReturnInfo;
import com.example.eos.bean.User;
import com.example.eos.bean.UserFollow;
import com.example.eos.mapper.UserFollowMapper;
import com.example.eos.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserFollowService {

    private UserFollowMapper userFollowMapper;
    private UserMapper userMapper;

    @Autowired
    public UserFollowService(UserFollowMapper userFollowMapper, UserMapper userMapper){
        this.userFollowMapper = userFollowMapper;
        this.userMapper = userMapper;
    }

    //查询用户的关注/粉丝
    public ReturnInfo findUserFollowsOrFans(String userid, String findtype){
        if(userMapper.findByUserid(userid)==null){
            return ReturnInfo.info2("用户不存在","");
        }else {
            List<UserFollow> userFollows = new ArrayList<>();
            if(findtype.equals("关注")){
                userFollows = userFollowMapper.findFollowByUserid(userid);
            }
            if(findtype.equals("粉丝")){
                userFollows = userFollowMapper.findFansByUserid(userid);
            }
            ArrayList<String> strArray = new ArrayList<> ();
            for(UserFollow userFollow : userFollows){
                strArray.add(userFollow.getFollowid());
            }
            return ReturnInfo.info2("正确",strArray);
        }
    }

    //用户添加关注
    public ReturnInfo addUserFollow(String followid){
        Subject subject = SecurityUtils.getSubject();
        User user =(User) subject.getPrincipal();
        if(userMapper.findByUserid(followid)==null){
            return ReturnInfo.info1("用户不存在");
        }
        if(userFollowMapper.findByUseridAndFollowid(user.getUserid(),followid)!=null){
            return ReturnInfo.info1("已关注该用户");
        }
        UserFollow userFollow = new UserFollow(user.getUserid(),followid);
        userFollowMapper.save(userFollow);
        userMapper.addFollownum(user.getUserid());
        userMapper.addFansnum(followid);
        return ReturnInfo.info1("成功");
    }

    //删除用户关注
    public ReturnInfo deleteUserFollow(String followid){
        Subject subject = SecurityUtils.getSubject();
        User user =(User) subject.getPrincipal();
        if(userMapper.findByUserid(followid)==null){
            return ReturnInfo.info1("用户不存在");
        }
        if(userFollowMapper.findByUseridAndFollowid(user.getUserid(),followid)==null){
            return ReturnInfo.info1("未关注该用户");
        }
        userFollowMapper.deleteByUseridAndFollowid(user.getUserid(),followid);
        userMapper.minusFollownum(user.getUserid());
        userMapper.minusFansnum(followid);
        return ReturnInfo.info1("成功");
    }

}
